package xyz.yq56.easytool.utils.ab_test;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;

import xyz.yq56.easytool.utils.collection.CollectUtil;
import xyz.yq56.easytool.utils.fori.ForUtil;
import xyz.yq56.easytool.utils.id.uuid.UUID;
import xyz.yq56.easytool.utils.string.TextUtils;

/**
 * @author yi qiang
 * @date 2021/12/5 2:19
 */
public class AbTestUtil {

    private AbTestUtil() {
    }

    /**
     * abTest分组工具类
     *
     * @param testType   测试类型,比如分发测试
     * @param uuid       设备id或用户id等
     * @param groupCount 分组数量
     * @return 分组编号
     */
    public static int abTestGroup(String testType, String uuid, int groupCount) {
        if (TextUtils.isEmpty(uuid) || groupCount <= 0) {
            throw new AbTestException("Illegal Argument");
        }
        int hashCode = DigestUtils.sha1Hex(testType + uuid).hashCode();
        return Math.abs(hashCode) % groupCount;
    }

    /**
     * 根据比例切分流量
     * <br> rate为A组比例
     *
     * @param testType 测试类型,比如分发测试
     * @param uuid     设备id或用户id等
     * @param rate     比例省略%,比如50%->50
     * @return 分组编号
     */
    public static int abTestGroupByRate(String testType, String uuid, int rate) {
        int group = abTestGroup(testType, uuid, 100);
        return group < rate ? 0 : 1;
    }

    private static class AbTestException extends RuntimeException {
        public AbTestException(String msg) {
            super(msg);
        }
    }

    public static void main(String[] args) {
        List<Integer> test = ForUtil.forList(1000, i ->
                abTestGroupByRate("test", UUID.randomUUID().toString(), 40));
        System.out.println(CollectUtil.groupCount(test, item -> item));
    }

}
